#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/9/23 12:07
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import datetime
import random
import threading
import time
import traceback
from urllib import parse

import requests

from auto_battle_room import YamlControl


class AutoJoinRoll:
    def __init__(self):
        """获取"""
        self.config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
        self.day_roll_user_limit = self.config_data["day_roll_user_limit"]  # 获取roll房用户限制
        self.week_roll_user_limit = self.config_data["week_roll_user_limit"]  # 获取roll房用户限制

        self.host = self.config_data["admin_host"]  # 获取环境域名
        self.token = self.config_data["admin_token"]  # 获取后台token
        self.post_headers = {
            "Token": self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }
        self.get_headers = {
            "Token": self.token
        }

        self.uid_list = ['8537', '8538', '8539', '8540', '8541', '8542', '8543', '8544', '8545', '8546',
                         '8547', '8548', '8549', '8550', '8551', '8552', '8554', '8555', '8556', '8557',
                         '8558', '8559', '8560', '8561', '8562', '8563', '8564', '8565', '8566', '8567',
                         '8568', '8569', '8570', '8571', '8572', '8573', '8574', '8575', '8576', '8577',
                         '8578', '8579', '8580', '8581', '8582', '8583', '8584', '8585', '8586', '8587',
                         '8588', '8589', '8590', '8591', '8592', '8593', '8728', '8595', '8596', '8597',
                         '8729', '8599', '8600', '8601', '8602', '8603', '8604', '8605', '8606', '8607',
                         '8608', '8609', '8610', '8611', '8612', '8613', '8730', '8615', '8616', '8731',
                         '8618', '8619', '8620', '8621', '8622', '8623', '8624', '8625', '8732', '8627',
                         '8628', '8629', '8630', '8631', '8632', '8633', '8634', '8635', '8636', '8637',
                         '8638', '8639', '8640', '8641', '8642', '8643', '8644', '8645', '8646', '8647',
                         '8733', '8649', '8650', '8734', '8652', '8653', '8654', '8655', '8656', '8657',
                         '8736', '8659', '8660', '8661', '8662', '8737', '8664', '8665', '8666', '8667',
                         '8668', '8669', '8670', '8671', '8672', '8673', '8674', '8675', '8676', '8677',
                         '8678', '8679', '8680', '8738', '8682', '8683', '8684', '8685', '8739', '8687',
                         '8688', '8740', '8690', '8691', '8692', '8693', '8694', '8695', '8696', '8697',
                         '8698', '8699', '8700', '8701', '8702', '8703', '8704', '8705', '8706', '8707',
                         '8708', '8709', '8710', '8711', '8712', '8713', '8714', '8715', '8716', '8717',
                         '8718', '8719', '8720', '8721', '8722', '8723', '8724', '8725', '8726', '8727',
                         '8897', '8898', '8899', '8915', '8901', '8902', '8903', '8904', '8905', '8906',
                         '8907', '8908', '8909', '8910', '8916', '8917', '8913', '8914', '8918', '8919',
                         '8920', '8921', '8922', '8923', '8924', '8925', '8926', '8927', '8928', '8929',
                         '9000', '8931', '8932', '8933', '8934', '8935', '9001', '8937', '8938', '8939',
                         '8940', '8941', '8942', '8943', '8944', '8945', '9002', '8947', '8948', '8949',
                         '8950', '8951', '8952', '8953', '8954', '8955', '8956', '8957', '8958', '9003',
                         '8960', '8961', '8962', '8963', '8964', '8965', '8966', '8967', '8968', '8969',
                         '8970', '8971', '8972', '8973', '9004', '8975', '8976', '8977', '8978', '9005',
                         '8980', '8981', '8982', '8983', '8984', '8985', '8986', '8987', '8988', '8989',
                         '8990', '8991', '8992', '8993', '8994', '8995', '8996', '8997', '8998']

    def get_user_id(self, phone):
        """获取用户ID"""
        url = "/api/sys/user/customer/page"
        data = {
            "phone": phone,
            "customerType": 2,
            "page": 1,
            "pageSize": 10,
            "current": 1
        }
        response = requests.get(url=self.host + url, params=data, headers=self.get_headers)
        return response.json()["data"]["pageData"][0]["id"]

    def get_user_info(self, user_id):
        """获取用户信息"""
        url = "/api/sys/user/customer/userInfo"
        data = {
            "id": user_id
        }
        return requests.get(url=self.host + url, params=data, headers=self.get_headers).json()["data"]

    def add_roll_user(self, roll_id, user_id):
        """新增roll房用户"""
        res = self.get_user_info(user_id)
        url = "/api/sys/roll/addUser"
        data = {
            "rollId": roll_id,
            "customerId": user_id,
            "phone": res["phone"],
            "nickname": res["nickname"],
            "remark": res["remark"],
            "headPic": res["headPic"],
        }
        data = parse.urlencode(data)
        requests.post(url=self.host + url, data=data, headers=self.post_headers)

    def get_roll_id(self):
        """获取roll房ID"""
        url = "/api/sys/roll/page"
        data = {
            "page": 1,
            "papageSizege": 50,
            "current": 1,
            "state": 1
        }
        try:
            response = requests.get(url=self.host + url, params=data, headers=self.get_headers)
            day_roll_id_list = []
            week_roll_id_list = []
            month_roll_id_list = []
            if response.json()["status"] == 0:
                for roll in response.json()["data"]["pageData"]:
                    if "日" in roll["title"]:
                        day_roll_id_list.append(roll["id"])
                    elif "周" in roll["title"]:
                        week_roll_id_list.append(roll["id"])
                    elif "月" in roll["title"]:
                        month_roll_id_list.append(roll["id"])
                return day_roll_id_list, week_roll_id_list, month_roll_id_list
        except Exception as e:
            print(f"获取roll房ID报错：{e}")
            traceback.print_exc()
            return []

    def get_roll_detail(self, roll_id):
        """获取roll房详情"""
        url = "/api/sys/roll/rollGiftDetail"
        data = {
            "rollId": roll_id
        }
        data = parse.urlencode(data)
        res = requests.post(url=self.host + url, data=data, headers=self.post_headers)
        if res and res.json()["status"] == 0:
            return res.json()["data"]
        else:
            return None


auto_join_roll = AutoJoinRoll()
uid_list = auto_join_roll.uid_list
day_roll_user_limit = auto_join_roll.day_roll_user_limit
week_roll_user_limit = auto_join_roll.week_roll_user_limit
# 从用户列表中随机取出一定数量的用户
day_user_list = random.sample(uid_list, random.randint(int(day_roll_user_limit)-1, int(day_roll_user_limit+2)))
week_user_list = random.sample(uid_list, random.randint(int(week_roll_user_limit)-1, int(week_roll_user_limit+1)))
# user_list3 = random.sample(uid_list, random.randint(int(roll_user_limit)-5, int(roll_user_limit+5)))
day_roll_list, week_roll_list, month_roll_list = auto_join_roll.get_roll_id()


# 四个进程同时分别执行加小时、日、周、月roll房用户
def add_day_roll_user():
    """新增日roll房用户"""
    # 处理入roll
    h_stop_time = 2  # int(60 * 60 / len(day_user_list))
    if len(day_roll_list) > 0:
        for uid in day_user_list:
            for roll_id in day_roll_list:
                res = auto_join_roll.get_roll_detail(roll_id)
                if res is not None and res["state"] == 1:  # roll房开启状态
                    try:
                        auto_join_roll.add_roll_user(roll_id, uid)
                        print(f"已添加用户{uid}到日roll房{roll_id}")
                        # h_stop_time = 3
                        time.sleep(random.randint(h_stop_time-1, h_stop_time))
                    except Exception as e:
                        print(f"添加用户报错：{e}")
                        continue


def add_week_roll_user():
    """新增周roll房用户"""
    # 处理周roll
    w_stop_time = 3  # int(60 * 60 / len(week_user_list))
    if len(week_roll_list) > 0:
        for uid in week_user_list:
            for roll_id in week_roll_list:
                res = auto_join_roll.get_roll_detail(roll_id)
                if res is not None and res["state"] == 1:  # roll房开启状态
                    try:
                        auto_join_roll.add_roll_user(roll_id, uid)
                        print(f"已添加用户{uid}到周roll房{roll_id}")
                        # w_stop_time = 5
                        time.sleep(random.randint(w_stop_time-1, w_stop_time+1))
                    except Exception as e:
                        print(f"添加用户报错：{e}")
                        continue


# 四个进程同时分别执行加小时、日、周、月roll房用户
# t2 = threading.Thread(target=add_week_roll_user())
t1 = threading.Thread(target=add_day_roll_user())

# 启动创建房间和参加房间的线程
# t2.start()
t1.start()

# 等两个程序结束
# t2.join()
t1.join()

now = datetime.datetime.now()
end_time = now.strftime("%Y-%m-%d %H:%M:%S")

print("本轮roll工作到此结束啦")
print(f"end time: {end_time}")


if __name__ == '__main__':
    # 手动批量加roll 142,83
    add_day_roll_user()
    # auto_join_roll = AutoJoinRoll()
    # p1 = 26111111110
    # p2 = 26111111399
    # uid = []
    # i = 0
    # for p in range(p1, p2):
    #     res = auto_join_roll.get_user_id(p)
    #     i += 1
    #     uid.append(res)
    #     if i % 10 == 0:
    #         print(f"已获取{i}个用户ID")
    #         # print(uid)
    # print(uid)

